package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduorder.entity.TOrder;
import com.atguigu.eduorder.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author hwt
 * @since 2022-10-02
 */
@RestController
@RequestMapping("/eduorder/order")
public class TOrderController {

    @Resource
    private TOrderService orderService;

    // 生成订单的方法
    @PostMapping("createOrder/{courseId}")
    public R createOrder(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        // 获取到用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        assert memberId != null;
        // 创建订单，返回订单号码
        String OrderCode = orderService.createOrder(courseId, memberId);
        return R.ok().data("OrderCode", OrderCode);
    }

    // 根据 id 查询订单接口
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable("orderId") String orderId) {
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        // 注意，订单id并不是主键！！！
        wrapper.eq("order_no", orderId);
        TOrder one = orderService.getOne(wrapper);

        return R.ok().data("item", one);
    }

    // 根据课程 id 和 用户 id 查询是否购买了该课程
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable("courseId") String courseId,
                               @PathVariable("memberId") String memberId) {

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        wrapper.eq("status",1); // 查询已经支付了的记录

        int count = orderService.count(wrapper);

        return count>0;

    }

}

